﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

//using ESRI.ArcGIS.ADF;


public partial class Services_getCustomRSIndex : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/xml";
        Response.Charset = "utf-8";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");

        string imageId = Request.QueryString[0].ToString();
        string blockSize = Request.QueryString[1].ToString().Remove(0, 4);
        string formula = Request.QueryString[2].ToString();
        string bandList ="[" +  Request.QueryString[3].ToString().Trim() + "]";
        



        string result = "";
        string SP_File_Name = "";
        DateTime ImageDate = new DateTime();


        string resultXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "\n";
        //resultXml += "<ImageList>" + "\n";

        try
        {
            string queryString = "select SP_FILE_NAME,IMAGEDATE from rs.DISTRICT_IMAGE_SP_REF where imageid like '%" + imageId + "%'";
            DataSet ds = OracleDataBase.Query(queryString);
            DataTable dt = ds.Tables[0];
            if (dt.Rows.Count == 1)
            {
                SP_File_Name = dt.Rows[0][0].ToString();
                ImageDate = Convert.ToDateTime(dt.Rows[0][1].ToString());
            }
            else
            {
                resultXml += "<url>Error! Can't find your request image on server,please check again!</url>";
            }
        }
        catch (Exception ex)
        {
            resultXml += "<url>Error!" + ex.Message.ToString() + "</url>";
        }
        //string IMAGE_NAME = dt.Rows[0][2].ToString();

        try
        {
            string DataRootPath = "D:\\Project\\rscrop\\data\\";
            
            //RemoteSensingIndex.RSI.ReSamplePointRemoteSensingIndex pRsi = new RemoteSensingIndex.RSI.ReSamplePointRemoteSensingIndex();
            IntPtr intPtr = new IntPtr();
            RSIndexCalculator.IndexCalculator indexCalculator = new RSIndexCalculator.IndexCalculator(intPtr);
            //string res = indexCalculator.CalcuSamplePointIndex(DataRootPath + "image\\" + imageId + ".tif",
            //                                                        DataRootPath + "shape\\" + SP_File_Name + ".shp",
            //                                                        blockSize,
            //                                                        DataRootPath + "Result\\MiddleResult.tif",
            //                                                        DataRootPath + "Result\\LastResult",
            //                                                        DataRootPath + "Result\\ResultText.txt",
            //                                                        formula,
            //                                                        bandList,
            //                                                        DataRootPath + "Result\\Log.log");
            //if (res == "0")
            //{
                StreamReader sr = new StreamReader(DataRootPath + "Result\\ResultText.txt");
                ArrayList SPIndex = new ArrayList();
                string point = sr.ReadLine().Trim();
                try
                {
                    while (point != null)
                    {
                        SPIndex.Add(point.Trim());
                        point = sr.ReadLine();

                    }
                    sr.Close();
                }
                catch (FieldAccessException ex)
                {
                    sr.Close();
                }

                string samplePointInfo = indexCalculator.getSamplePointInfo(SP_File_Name,DataRootPath + "shape\\" );
                string[] pointInfoArray = samplePointInfo.Split(';');
                string[] pointNameArray = new string[pointInfoArray.Length - 1];
                string[] pointLatArray = new string[pointInfoArray.Length - 1];
                string[] pointLonArray = new string[pointInfoArray.Length - 1];
                string[] temp = new string[3];
                for (int i = 0; i < pointInfoArray.Length - 1; i++)
                {
                    temp = pointInfoArray[i].Split(',');
                    pointNameArray[i] = temp[0];
                    pointLatArray[i] = temp[1];
                    pointLonArray[i] = temp[2];
                }


                string strSql = "";//update rs.sp_rsindex set CustomIndex = " + (float)SPIndex[i] + " where POINTNAME = '" + pointNameArray[i] + "' and SAMPDATE = " + ImageDate;
                resultXml += "<Parcels>\n";
                for (int i = 0; i < SPIndex.Count; i++)
                {
                    resultXml += "<Parcel name = '" + pointNameArray[i] + "' Lat = '" + pointLatArray[i] + "' Lon = '" + pointLonArray[i] + "' value = '" + SPIndex[i].ToString() + "'/>\n";
                    strSql = "update rs.sp_rsindex set CustomIndex = " + Convert.ToSingle(SPIndex[i]) + " where POINTID = '" + pointNameArray[i] + "' and SAMPDATE = to_date('" + ImageDate.ToShortDateString() + "','yyyy-mm-dd')";//sampdate=to_date('" + samplingDateString + "','yyyy-mm-dd')";
                    OracleDataBase.ExecuteSql(strSql);
                }
                resultXml += "</Parcels>\n";

            //}




            //if (pRsi.init())
            //{
            //    //string baseLocation = System.Configuration.ConfigurationManager.AppSettings["DEFAULT_LOCATION"];// Server..MapPath("../"); //Environment.CurrentDirectory;
            //    string baseLocation = Server.MapPath("../");
            //    string sdeServer = System.Configuration.ConfigurationManager.AppSettings["SDE_SERVER"];
            //    string sdeInstance = System.Configuration.ConfigurationManager.AppSettings["SDE_INSTANCE"];
            //    string sdeUser = System.Configuration.ConfigurationManager.AppSettings["SDE_USER"];
            //    string sdePWD = System.Configuration.ConfigurationManager.AppSettings["SDE_PWD"];
            //    string OraConnString = System.Configuration.ConfigurationManager.ConnectionStrings["OracleConnectionString"].ToString();

            //    //string sampleFileLocation = SP_FILE_NAME;

            //    result = pRsi.GetIndexDataSet(SP_File_Name, imageId, baseLocation + "data\\", blockSize, OraConnString, sdeServer, sdeInstance, sdeUser, sdePWD, ImageDate);

            //    XmlDocument xmlDoc = new XmlDocument();
            //    xmlDoc.Load(result);
            //    XmlNodeList xmlNodeList = xmlDoc.GetElementsByTagName("Parcel");
            //    int nChildren = xmlNodeList.Count;
            //    int nAttributes = xmlNodeList[0].ChildNodes.Count;

            //    resultXml += "<" + xmlDoc.ChildNodes[0].Name + ">" + "\n";
            //    for (int i = 0; i < nChildren; i++)
            //    {
            //        resultXml += "<" + xmlNodeList[i].Name + " ";
            //        for (int j = 0; j < nAttributes; j++)
            //        {
            //            resultXml += xmlNodeList[i].ChildNodes[j].Name + "='" + xmlNodeList[i].ChildNodes[j].FirstChild.Value + "' ";
            //        }
            //        resultXml += " />" + "\n";
            //    }
            //    resultXml += "</" + xmlDoc.ChildNodes[0].Name + ">" + "\n";
            //    //resultXml += xmlDoc.InnerXml;// "<url>" + result + "</url>";
            //    //Response.Write(resultXml);
            //}
            //else
            //{
            //    resultXml += "<url>Error! Server Machine is out of license!</url>";
            //}
        }
        catch (ExecutionEngineException ex)
        {
            resultXml += "<url>Error!" + ex.Message.ToString() + "</url>";
        }
        Response.Write(resultXml);
    }
}
